﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class CompletePurchase : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        if (Session["UserLogIn"] == null)
            Response.Redirect("Login.aspx");
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["orderitems"] != null)
        {
            Total temp = new Total();
            temp = (Total)Session["mytotal"];
            Master.OrderLabel = (string)Session["orderitems"];
            Master.TotalLabel = "Total: " + String.Format("{0:C}", temp.CurrentTotal);

            Session["customerid"] = Convert.ToInt32(CustomerInfoGridView.Rows[0].Cells[0].Text);
        }

        if (PaymentInfoGridView.Rows.Count == 0) NoPaymentPanel.Visible = true;
        else NoPaymentPanel.Visible = false;

        CompletePurchaseLabel.Visible = false;
    }

    protected void ClearButton_Click(object sender, EventArgs e)
    {
        Session["UserLogIn"] = null;
        Session["orderitems"] = null;
        Session["mytotal"] = null;
        Session["customerid"] = null;

        Response.Redirect("Default.aspx");
    }

    protected void EnterButton_Click(object sender, EventArgs e)
    {
        AddPaymentButton.Visible = true;
        NoPaymentPanel.Visible = false;

        try 
        {

            string connect = System.Configuration.ConfigurationManager.ConnectionStrings["RSardinas_6118_ConnString"].ConnectionString;
            SqlConnection scn = new SqlConnection(connect);
            scn.Open();

            string sp = "AddNewPaymentEntry";

            
            

            SqlCommand spcmd = new SqlCommand(sp, scn);
            spcmd.CommandType = CommandType.StoredProcedure;

 
            SqlParameter custid = new SqlParameter("@customerid", (int)Session["customerid"]);
            SqlParameter cardname = new SqlParameter("@cardname", CNameTextBox.Text);
            SqlParameter cardnum = new SqlParameter("@cardnumber", Convert.ToInt64(CNumTextBox.Text));
           
            spcmd.Parameters.Add(custid);
            spcmd.Parameters.Add(cardname);
            spcmd.Parameters.Add(cardnum);

            spcmd.ExecuteNonQuery();

            scn.Close();
        }
        catch (SqlException x)
        {
            
        }
        Response.Redirect("CompletePurchase.aspx");
    }

    protected void PaymentInfoGridView_SelectedIndexChanged(object sender, EventArgs e)
    {
        NoPaymentPanel.Visible = false;
        AddPaymentButton.Visible = false;
        CompletePurchaseLabel.Visible = true;

        string lastfour = PaymentInfoGridView.Rows[PaymentInfoGridView.SelectedIndex].Cells[4].Text.ToString();
        lastfour = lastfour.Substring(lastfour.Length - 4);

        string thanks = "Thank you for your purchase. Below are your order details.<br />";

        thanks += "Name: " + CustomerInfoGridView.Rows[0].Cells[1].Text.ToString() + " "
                        + CustomerInfoGridView.Rows[0].Cells[2].Text.ToString() + "<br />";

        thanks += "Address: " + CustomerInfoGridView.Rows[0].Cells[3].Text.ToString() +"<br />"
                    + CustomerInfoGridView.Rows[0].Cells[4].Text.ToString() + " "
                    + CustomerInfoGridView.Rows[0].Cells[5].Text.ToString() + " "
                    + CustomerInfoGridView.Rows[0].Cells[6].Text.ToString() + "<br />";

        thanks += "Card Name: " + PaymentInfoGridView.Rows[PaymentInfoGridView.SelectedIndex].Cells[3].Text.ToString()
                    + " ...." + lastfour + "<br /> <br />";

        thanks += Master.OrderLabel + "<br />";

        Total temp = (Total)Session["mytotal"];
        thanks += "Total with tax: " + String.Format("{0:C}",(temp.CurrentTotal * 1.1M));

        Master.OrderLabel = "";
        Master.TotalLabel = "";

        CompletePurchaseLabel.Text = thanks;

        //update database
        processPayment();

        Session["UserLogIn"] = null;
        Session["orderitems"] = null;
        Session["mytotal"] = null;
        Session["customerid"] = null;

    }


    protected void AddPaymentButton_Click(object sender, EventArgs e)
    {
        NoPaymentPanel.Visible = true;
        AddPaymentButton.Visible = false;
    }


    /**
     * Add order to database
     */
    private void processPayment()
    {
        DataClassesDataContext db = new DataClassesDataContext();
        List<CART_ENTRY> mycartentries = new List<CART_ENTRY>();
        COUPON mycoupon = new COUPON();
        Total temp2 = (Total)Session["mytotal"];
        decimal taxamount = .1M * temp2.CurrentTotal;
        int cartid;

        //create cart and insert into table
        CART mycart = new CART();
        mycart.CREATE_DATE = DateTime.Now;
        mycart.ORDER_DATE = DateTime.Now;
        mycart.DELIVER_ON = DateTime.Now;
        mycart.CID = Convert.ToInt32(CustomerInfoGridView.Rows[0].Cells[0].Text);
        mycart.DISCOUNT = null;
        mycart.IS_CARRYOUT = false;
        mycart.IS_ORDER_FORNOW = true;
        mycart.IS_ORDER_PLACED = true;
        mycart.TAXES = Convert.ToDouble(taxamount);
        mycart.CART_TOTAL = Convert.ToDouble(taxamount + temp2.CurrentTotal);
        mycart.DELIVERY_ADDRESS = CustomerInfoGridView.Rows[0].Cells[3].Text.ToString() + ", "
                    + CustomerInfoGridView.Rows[0].Cells[4].Text.ToString() + ", "
                    + CustomerInfoGridView.Rows[0].Cells[5].Text.ToString() + ". "
                    + CustomerInfoGridView.Rows[0].Cells[6].Text.ToString();

        db.CARTs.InsertOnSubmit(mycart);

        try
        {
            db.SubmitChanges();
        }
        catch (Exception e)
        {
        }

        cartid = (from crt in db.CARTs
                  where crt.DELIVER_ON == mycart.DELIVER_ON
                  && crt.CID == mycart.CID
                  && crt.CART_TOTAL == mycart.CART_TOTAL
                  select crt.CART_ID).FirstOrDefault();

        //add cart entries
        OrderItemsMain myitems = (OrderItemsMain) Session["products"];
        for(int i = 0; i < myitems.OrderItems.Count; i++)
        {
            //get product
            PRODUCT temp = (from pr in db.PRODUCTs
                        where pr.DESCRIP == myitems.OrderItems.ElementAt(i)
                        select pr).FirstOrDefault();

            //use product to make a cart entry
            CART_ENTRY temp3 = new CART_ENTRY();
            temp3.CART_ID = cartid;
            temp3.PID = temp.PID;
            temp3.DESCRIP = temp.DESCRIP;
            temp3.PRICE = temp.PRICE;
            temp3.ENTRY_DATE = mycart.CREATE_DATE;
            temp3.IS_ORDER_PLACED = true;
            temp3.TYPE = temp.TYPE;
            temp3.PIZZA_PID = 0;
            temp3.QTY = 1;
            temp3.LINE_TOTAL = temp3.QTY * temp3.PRICE;

            db.CART_ENTRies.InsertOnSubmit(temp3);

            try
            {
                db.SubmitChanges();
            }
            catch (Exception e)
            {

            }


        }
        
    }

  
}